﻿using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Microsoft.AspNetCore.Http;

namespace Admin.NET.Application;

/// <summary>
/// 设备运行异常指令日志服务
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class DeviceErrorCommandLogService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<DeviceErrorCommandLog> _deviceErrorCommandLogRep;

    public DeviceErrorCommandLogService(SqlSugarRepository<DeviceErrorCommandLog> deviceErrorCommandLogRep)
    {
        _deviceErrorCommandLogRep = deviceErrorCommandLogRep;
    }

    /// <summary>
    /// 分页查询设备运行异常指令日志
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Page")]
    [DisplayName("分页查询设备运行异常指令日志")]
    public async Task<SqlSugarPagedList<DeviceErrorCommandLogOutput>> Page(PageDeviceErrorCommandLogInput input)
    {
        input.SearchKey = input.SearchKey?.Trim();
        var query = _deviceErrorCommandLogRep.AsQueryable()
            .WhereIF(!string.IsNullOrEmpty(input.SearchKey), u =>
                u.Title.Contains(input.SearchKey)
                || u.ReceiveText.Contains(input.SearchKey)
                || u.Ip.Contains(input.SearchKey)
            )
            .WhereIF(input.GateWayId > 0, u => u.GateWayId == input.GateWayId)
            .WhereIF(input.DeviceId > 0, u => u.DeviceId == input.DeviceId)
            .WhereIF(!string.IsNullOrWhiteSpace(input.Title), u => u.Title.Contains(input.Title.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ReceiveText), u => u.ReceiveText.Contains(input.ReceiveText.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Ip), u => u.Ip.Contains(input.Ip.Trim()))
            //处理外键和TreeSelector相关字段的连接
            .LeftJoin<DeviceGateWay>((u, gatewayid) => u.GateWayId == gatewayid.Id)
            .LeftJoin<DeviceInfo>((u, gatewayid, deviceid) => u.DeviceId == deviceid.Id)
            .Select((u, gatewayid, deviceid) => new DeviceErrorCommandLogOutput
            {
                Id = u.Id,
                GateWayId = u.GateWayId,
                GateWayIdGateWayName = gatewayid.GateWayName,
                DeviceId = u.DeviceId,
                DeviceIdDeviceName = deviceid.DeviceName,
                Title = u.Title,
                ReceiveText = u.ReceiveText,
                Ip = u.Ip,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });
        return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 增加设备运行异常指令日志
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Add")]
    [DisplayName("增加设备运行异常指令日志")]
    public async Task<long> Add(AddDeviceErrorCommandLogInput input)
    {
        var entity = input.Adapt<DeviceErrorCommandLog>();
        await _deviceErrorCommandLogRep.InsertAsync(entity);
        return entity.Id;
    }

    public async Task<long> AddNoThrow(AddDeviceErrorCommandLogInput input)
    {
        try
        {
          return await Add(input);
        }
        catch (Exception ex)
        {
            return 0;
           
        }
    }

    /// <summary>
    /// 删除设备运行异常指令日志
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Delete")]
    [DisplayName("删除设备运行异常指令日志")]
    public async Task Delete(DeleteDeviceErrorCommandLogInput input)
    {
        var entity = await _deviceErrorCommandLogRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _deviceErrorCommandLogRep.FakeDeleteAsync(entity);   //假删除
        //await _deviceErrorCommandLogRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 更新设备运行异常指令日志
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Update")]
    [DisplayName("更新设备运行异常指令日志")]
    public async Task Update(UpdateDeviceErrorCommandLogInput input)
    {
        var entity = input.Adapt<DeviceErrorCommandLog>();
        await _deviceErrorCommandLogRep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
    }

    /// <summary>
    /// 获取设备运行异常指令日志
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "Detail")]
    [DisplayName("获取设备运行异常指令日志")]
    public async Task<DeviceErrorCommandLog> Detail([FromQuery] QueryByIdDeviceErrorCommandLogInput input)
    {
        return await _deviceErrorCommandLogRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 获取设备运行异常指令日志列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "List")]
    [DisplayName("获取设备运行异常指令日志列表")]
    public async Task<List<DeviceErrorCommandLogOutput>> List([FromQuery] PageDeviceErrorCommandLogInput input)
    {
        return await _deviceErrorCommandLogRep.AsQueryable().Select<DeviceErrorCommandLogOutput>().ToListAsync();
    }

    /// <summary>
    /// 获取关联网关id列表
    /// </summary>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "DeviceGateWayGateWayIdDropdown"), HttpGet]
    [DisplayName("获取关联网关id列表")]
    public async Task<dynamic> DeviceGateWayGateWayIdDropdown()
    {
        return await _deviceErrorCommandLogRep.Context.Queryable<DeviceGateWay>()
                .Select(u => new
                {
                    Label = u.GateWayName,
                    Value = u.Id
                }
                ).ToListAsync();
    }

    /// <summary>
    /// 获取关联设备id列表
    /// </summary>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "DeviceInfoDeviceIdDropdown"), HttpGet]
    [DisplayName("获取关联设备id列表")]
    public async Task<dynamic> DeviceInfoDeviceIdDropdown()
    {
        return await _deviceErrorCommandLogRep.Context.Queryable<DeviceInfo>()
                .Select(u => new
                {
                    Label = u.DeviceName,
                    Value = u.Id
                }
                ).ToListAsync();
    }

    /// <summary>
    /// 保留最新的5000条设备运行日志
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "TrimDeviceErrorCommandLog")]
    [DisplayName("保留最新的5000条设备运行日志")]
    public async Task TrimDeviceErrorCommandLog()
    {
        var totalLogs = await _deviceErrorCommandLogRep.CountAsync(u => true);
        if (totalLogs > 10000)
        {
            _deviceErrorCommandLogRep.Context.CopyNew().Deleteable<DeviceErrorCommandLog>().In(it => it.Id,
                   _deviceErrorCommandLogRep.Context.CopyNew().Queryable<DeviceErrorCommandLog>()
                  .Take(totalLogs - 5000)
                  .Select(it => it.Id)).ExecuteCommand();
        }


    }

    [NonAction]
    public async Task AddDeviceErrorCommandLogList(List<AddDeviceErrorCommandLogInput> addDeviceErrorCommandLogInputs)
    {
        var entity = addDeviceErrorCommandLogInputs.Adapt<List<DeviceErrorCommandLog>>();
        await _deviceErrorCommandLogRep.Context.CopyNew().Insertable(entity).ExecuteCommandAsync();

    }
}